
//
//  String+Extension.swift
//  03.处理来源
//
//  Created by bing on 16/3/30.
//  Copyright © 2016年 bing. All rights reserved.
//

import UIKit

extension String {
    
     func sinaSource() -> String {
        // 从字符串里面截取 iPhone 6
        //                              <a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>
//        let source = "<a href=\"http://app.weibo.com/t/feed/3o33sO\" rel=\"nofollow\">iPhone 6</a>nofollow\">iPhone 6</a>"
        let pattern = ">(.*?)<"
        
        let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        
        /* NSTextCheckingResult
        var numberOfRanges: Int { get } // 配到的的范围数量
        func rangeAtIndex(idx: Int) -> NSRange  // 通过下标来获取范围
        */
        
        let result = regular.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.characters.count))
        
        // 匹配的范围数量
        let count = result?.numberOfRanges ?? 0
        
        if count > 1 {
            let range = result!.rangeAtIndex(1)
            
            return (self as NSString).substringWithRange(range)
        }
        return "未知来源"
    }

}
